package com.lagou.edu.interceptor;

import com.lagou.edu.pojo.User;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


public class SecurityInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //登录校验
        if (request.getRequestURI().contains("login")){
            return true;
        }

        HttpSession session = request.getSession();
        Object user = session.getAttribute("username");
        if (user == null){
            //如果用户尚未登录，则直接跳转到登录页面

            request.getRequestDispatcher("/login.jsp").forward(request, response);
            //response.sendRedirect("/login.jsp");
            return false;
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

        System.out.println(ex.getMessage());
        System.out.println(ex.getLocalizedMessage());
        request.getRequestDispatcher("/login.jsp").forward(request, response);
    }
}
